<template>
  <view class="form-group pr-20">
    <input
      type="text"
      class="form-group-input"
      v-model="form.code"
      placeholder="请输入手机验证码"
      @input="inputCode"
      @change="inputCode"
    />
    <button
      class="form-group-button form-group-button-right"
      @click="getVerifyCaptcha"
      :disabled="resendWait > 0"
    >
      {{ buttonText }}
    </button>
    <verify-drag
      :visible.sync="verifyDragVisible"
      @change="verifyDragChange"
    ></verify-drag>
  </view>
</template>

<script>
  import { apiGetMobileVerifyCode } from "@/api/verify";

  export default {
    name: "VerifyMobile",
    props: {
      mobile: {
        type: [Number, String],
        default: "",
      },
      type: {
        // 验证类型
        type: [Number, String],
        default: "register", // register, login, reset
      },
      value: {
        type: [Number, String],
        default: "",
      },
    },
    data() {
      return {
        verifyDragVisible: false,
        isVerifyDrag: false,
        buttonText: "获取验证码",
        timer: null,
        resendWait: 0,
        form: {
          code: "",
        },
      };
    },
    watch: {
      value(newValue) {
        this.form.code = newValue;
      },
    },
    created() {
      this.form.code = this.value;
    },
    onShow() {},
    onUnload() {},
    methods: {
      verifyDragChange(e) {
        this.isVerifyDrag = e;

        if (e) {
          apiGetMobileVerifyCode({
            mobile: this.mobile,
            type: this.type, // 验证码类型 register 注册, login 登录, reset 修改手机号码
          }).then((res) => {
            uni.showToast({
              title: "验证码已发送",
              icon: "none",
            });
            this.resendWait = 60;
            this.timer = setInterval(() => {
              this.resendWait--;
              this.buttonText = this.resendWait + "s";
              if (this.resendWait <= 0) {
                clearInterval(this.timer);
                this.buttonText = "重新获取";
                this.isVerifyDrag = false;
              }
            }, 1000);
          });
        }
      },
      inputCode() {
        this.$emit("input", this.form.code);
      },
      getVerifyCaptcha() {
        if (!this.mobile) {
          uni.showToast({
            title: "请输入手机号码",
            icon: "none",
          });
          return;
        }

        if (!this.$utils.isMobile(this.mobile)) {
          uni.showToast({
            title: "请输入正确的手机号码",
            icon: "none",
          });
          return;
        }

        this.verifyDragVisible = true;
      },
    },
  };
</script>

<style lang="scss" scoped></style>
